package com.cn.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cn.component.treeData.TreeNode;
import com.cn.modules.menu.Menu;

public class TreeUtils {

	public static List<TreeNode> getTreeNode(List<TreeNode> list){
		 Map<String,List<TreeNode>> map= getParentNode(list);
		return  getTreeNodes(map, "0");
	}
	
	public static Map<String,List<TreeNode>> getParentNode(List<TreeNode> list){
		Map<String, List<TreeNode>> map=new HashMap<String, List<TreeNode>>();
		for (TreeNode treeNode : list) {
			if(map.get(treeNode.getParentId())!=null){
				map.get(treeNode.getParentId()).add(treeNode);
			}else{
				List<TreeNode> tmpList=new ArrayList<TreeNode>();
				tmpList.add(treeNode);
				map.put(treeNode.getParentId(), tmpList);
			}
		}
		return map;
	}
	
	public static List<TreeNode>  getTreeNodes(Map<String,List<TreeNode>> map, String parentId){
		if(map.get(parentId)!=null){
			List<TreeNode> list=map.get(parentId);
			for (TreeNode treeNode : list) {
				if(map.get(treeNode.getId())!=null){
					treeNode.setOpen(true);
					treeNode.setIsParent(true);
					treeNode.setNodes(map.get(treeNode.getId()));
					getTreeNodes(map, treeNode.getId());
				}else{
					treeNode.setNodes(null);
				}
			}
		}
		return map.get("0");
	}
	public static void main(String[] args) {
		TreeNode node=null;
		List<TreeNode> list=new ArrayList<TreeNode>();
		List<Menu> mList=Menu.dao.find("select * from MENU order by SORT_NUMBER");
		for (Menu menu : mList) {
			node=new TreeNode();
			node.setId(menu.getStr("CODE"));
			node.setName(menu.getStr("NAME"));
			node.setParentId(menu.getStr("PARENT_ID"));
			node.setChecked(true);
			list.add(node);
		}
		TreeUtils.getTreeNode(list);
	}
}
